import hashlib
import os

from flask import session, jsonify, render_template, request, redirect, url_for, current_app

from models import db
from models.index import Follow, User, Category, News
from utils.common import verify_suffix, create_uuid, upload_file_qiniu, delete
from views import user_blu


@user_blu.route("/focus")
def focus():
    # 当前登录的用户
    user_id = session.get("user_id", 0)
    # 当前文章的作者
    author_id = session.get("now_author_id")
    if not user_id:
        ret = {
            "errno": 1,
            "errmsg": "请先登录"
        }
        return jsonify(ret)

    follow = Follow()
    follow.followed_id = author_id
    follow.follower_id = user_id
    db.session.add(follow)
    db.session.commit()
    ret = {
        "errno": 0,
        "errmsg": "关注成功"
    }
    return jsonify(ret)


@user_blu.route("/focused")
def focused():
    # 当前登录的用户
    user_id = session.get("user_id", 0)
    # 当前文章的作者
    author_id = session.get("now_author_id")
    try:
        follow = db.session.query(Follow).filter(Follow.followed_id == author_id, Follow.follower_id == user_id).first()
        db.session.delete(follow)
        db.session.commit()
        ret = {
            "errno": 0,
            "errmsg": "取消关注成功"
        }
        return jsonify(ret)
    except:
        ret = {
            "errno": 1004,
            "errmsg": '取消关注失败'
        }
        return jsonify(ret)


@user_blu.route("/center")
def user_center():
    user_id = session.get('user_id')
    # 如果用户未登录，禁止访问用户中心
    if not user_id:
        return redirect(url_for('index.index'))
    user = db.session.query(User).filter(user_id == User.id).first()
    nick_name = user.nick_name
    avatar_url = user.avatar_url
    print(avatar_url)
    return render_template("index/user.html", nick_name=nick_name, avatar_url=avatar_url)


@user_blu.route("/user_base_info")
def user_base_info():
    return render_template("index/user_base_info.html")


@user_blu.route("/basic", methods=["POST"])
def user_basic():
    # 获取用户的新的信息
    nick_name = request.json.get("nick_name")
    signature = request.json.get("signature")
    gender = request.json.get("gender")

    # 获取当前用户的信息
    user_id = session.get("user_id")

    # 存储到数据库
    user = db.session.query(User).filter(User.id == user_id).first()
    if not user:
        ret = {
            "errno": 4002,
            "errmsg": "没有此用户"
        }

        return jsonify(ret)

    # 如果查询到此用户就修改数据
    user.nick_name = nick_name
    user.signature = signature
    user.gender = gender

    db.session.commit()
    ret = {
        "errno": 0,
        "errmsg": "修改成功..."
    }
    return jsonify(ret)


@user_blu.route("/user_pass_info")
def user_pass_info():
    return render_template('index/user_pass_info.html')


@user_blu.route("/password", methods=["POST"])
def user_password():
    # 1. 提取旧密码以及新密码
    new_password = request.json.get("new_password")
    old_password = request.json.get("old_password")

    # 2. 提取当前用户的id
    user_id = session.get("user_id")
    if not user_id:
        return jsonify({
            "errno": 4001,
            "errmsg": "请先登录"
        })

    # 2. 判断旧密码与数据中的当前存储的密码是否相同
    user = db.session.query(User).filter(User.id == user_id, User.password_hash == old_password).first()

    # 3. 如果相同，则修改
    if user:
        user.password_hash = new_password
        db.session.commit()
        ret = {
            "errno": 0,
            "errmsg": "修改成功"
        }

    else:
        ret = {
            "errno": 4004,
            "errmsg": "原密码错误！"
        }

    # 4. 返回json
    return jsonify(ret)


@user_blu.route("/user_pic_info")
def user_img():
    user_id = session.get("user_id")
    user = db.session.query(User).filter(User.id == user_id).first()

    return render_template('index/user_pic_info.html', user=user)


# @user_blu.route("/user/avatar", methods=["POST"])
# def save_head_img():
#     rq_content = request.files.get("avatar")
#     filename = rq_content.filename
#     if not verify_suffix(filename):
#         ret = {
#             "errno": 5001,
#             "errmsg": "文件类型有误"
#         }
#         return jsonify(ret)
#
#     # print(os.path.dirname(os.path.dirname(__file__)))
#     base_path = "/static/upload/"
#     # print(current_app.root_path)
#     name = create_uuid() + '.' + verify_suffix(filename)
#     filepath = current_app.root_path + base_path + name
#     rq_content.save(filepath)
#     user = db.session.query(User).filter(User.id == session.get("user_id")).first()
#     old_url = user.avatar_url
#     if old_url:
#         os.remove(current_app.root_path + old_url)
#     user.avatar_url = base_path + name
#     db.session.commit()
#     ret = {
#         "errno": 0,
#         "errmsg": "修改成功！",
#         "avatar_url": user.avatar_url
#     }
#     return jsonify(ret)


@user_blu.route("/avatar", methods=["POST"])
def save_head_img():
    rq_content = request.files.get("avatar")
    filename = rq_content.filename
    if not verify_suffix(filename):
        ret = {
            "errno": 5001,
            "errmsg": "文件类型有误"
        }
        return jsonify(ret)

    file_name = create_uuid() + '.' + verify_suffix(filename)
    img_url = upload_file_qiniu(file_name, rq_content)
    user = db.session.query(User).filter(User.id == session.get("user_id")).first()
    old_url = user.avatar_url
    if old_url:
        delete(old_url)
    user.avatar_url = img_url
    print(img_url)
    db.session.commit()
    ret = {
        "errno": 0,
        "errmsg": "修改成功！",
        "avatar_url": user.avatar_url
    }
    return jsonify(ret)


@user_blu.route("/user_follow")
def user_follow():
    # 获取当前需要展示的页数
    page = int(request.args.get("page", 1))
    user = db.session.query(User).filter(User.id == session.get("user_id")).first()
    paginate = user.followers.paginate(page, 2, False)
    return render_template("index/user_follow.html", paginate=paginate)


@user_blu.route("/user_collection")
def user_collection():
    # 获取页码
    page = int(request.args.get("page", 1))
    user = db.session.query(User).filter(User.id == session.get("user_id")).first()
    # 查询用户收藏的文章
    paginate = user.collection_news.paginate(page, 3, False)
    return render_template('index/user_collection.html', paginate=paginate)


@user_blu.route("/user_news_release")
def user_news_release():
    category_list = db.session.query(Category).filter(Category.id != 1).all()
    return render_template("index/user_news_release.html", category_list=category_list)


@user_blu.route("/release", methods=['POST'])
def new_release():
    title = request.form.get("title")
    category = request.form.get("category")
    digest = request.form.get("digest")
    content = request.form.get("content")
    f = request.files.get("index_image")

    print(title, category, digest, content, f)

    news = News()
    news.title = title
    news.category_id = category
    news.source = "个人发布"
    news.digest = digest
    news.content = content
    news.user_id = session.get("user_id")
    news.status = 1

    if f:
        file_name = create_uuid() + '.' + verify_suffix(f.filename)
        # 将路径改为static/upload下
        # path_file_name = "./static/upload/" + file_name

        # 用新的随机的名字当做图片的名字
        # f.save(path_file_name)

        # 将这个图片上传到七牛云
        qiniu_image_url = upload_file_qiniu(file_name, f)
        news.index_image_url = qiniu_image_url

    db.session.add(news)
    db.session.commit()

    ret = {
        "errno": 0,
        "errmsg": "成功"
    }

    return jsonify(ret)


@user_blu.route("/user_news_list")
def user_news_list():
    # 提取页码
    page = int(request.args.get("page", 1))
    user_id = session.get("user_id")
    user = db.session.query(User).filter(User.id == user_id).first()
    news_paginate = user.news.paginate(page, 1, False)
    return render_template("index/user_news_list.html", news_paginate=news_paginate)
